﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HCRS.DBACL;
using System.Threading;
using System.Text;
using Common;
using HCRS.Implementation;
using JinJiang.BookingEngine.Services;

namespace JinJiang.BookingEngine.Web.en
{
    public partial class Reservation : System.Web.UI.Page
    {
        private int ahid = 0;
        static string IATA = System.Configuration.ConfigurationManager.AppSettings["IATA"].ToString();
        static string PIATA = System.Configuration.ConfigurationManager.AppSettings["PIATA"].ToString();

        static decimal exchange = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["exchange"]);
        HCRS.Implementation.QueryXml _QueryXmlClass = new HCRS.Implementation.QueryXml();
        //UserClass _UserClass = new UserClass();
        HotelClass _HotelClass = new HotelClass();
        DataAccessLayer _DataAccessLayer = new DataAccessLayer();
        Functions _Functions = new Functions();
        CommonWeb _CommonClass = new CommonWeb();
        bool ppGua = false;
        bool ccGua = false;
        string userCredit = "";
        public string paymentHtml;
        int propertyID;
        string[] Day = new string[] { "Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat" };
        public string domain, domainurl;

        protected void Page_Load(object sender, EventArgs e)
        {
            PageCC.Visible = false;
            bool foundhotel;
            string rateinfo;
            pnlErr.Visible = false;

            if (Request.UrlReferrer != null)
                domain = FGBCommon.WebDomain(false, out domainurl);


            if (!(IsPostBack))
            {

                try
                {
                    int hotelID = Convert.ToInt32(Request.QueryString["HotelID"]);
                    csscontrel.InnerHtml = _HotelClass.GetCSSContrel(hotelID, 1);
                    slogan.InnerHtml = _HotelClass.GetSloganResv(hotelID, 1);
                    int nights;
                    int room = Convert.ToInt32(Request.QueryString["Rooms"]);
                    int adults = Convert.ToInt32(Request.QueryString["Adult"]);
                    int chileren = Convert.ToInt32(Request.QueryString["Child"]);

                    string spcode = Request.QueryString["spcode"] == null ? "" : Request.QueryString["spcode"];
                    string Chickindate = Request.QueryString["ChkIN"];
                    string Chickoutdate = Request.QueryString["ChkOUT"];
                    string rateCode = Request.QueryString["Ratecode"];
                    string roomCode = Request.QueryString["Roomcode"];
                    TimeSpan ts = Convert.ToDateTime(Chickoutdate) - Convert.ToDateTime(Chickindate);
                    nights = Convert.ToInt32(ts.TotalDays);
                    ahid = hotelID;
                    if (DataAcl.Common.isserverhotel(ahid.ToString()))
                        Userlogin1.Visible = true;

                    foundhotel = LoadHotelInfo(hotelID);
                    ckbNoSmooking.Attributes.Add("onclick", "NoSmooking(this);");
                    dpdCheckInTime.Attributes.Add("onChange", "validateCheckInTimeDo(this);");


                    string TempRate = "";

                    EnSearchHotelClass myHotelClass = new EnSearchHotelClass();


                    if (!myHotelClass.RateCodeAvailable(propertyID, "pid", rateCode, out TempRate))
                    {
                        Response.Write("No rates for this hotel at this moment（Error 001）");
                        Response.End();
                    }


                    if (TempRate == "" || TempRate == null)
                    {
                        Response.Write("No rates for this hotel at this moment（Error 002）");
                        Response.End();
                    }
                    else
                    {
                        rateCode = TempRate;
                    }


                    ViewState["h_fromurl"] = "prestige.jinjianghotels.com/en";
                    ViewState["h_subSource"] = "208";
                    ViewState["h_verifycode"] = Guid.NewGuid().ToString();
                    ViewState["h_hotelID"] = propertyID.ToString();
                    ViewState["h_children"] = chileren.ToString();
                    ViewState["h_property_id"] = propertyID.ToString();
                    ViewState["h_roomtype"] = roomCode;
                    ViewState["h_rateclass"] = rateCode;
                    ViewState["spcode"] = spcode;
                    ViewState["payment"] = "";


                    wd.Value = domainurl;
                    bodyBooking.Attributes.Add("onload", "fSetOutLinkIframe('" + domain + "');page_load()");
                    CheckRates(roomCode, rateCode, Chickindate, Chickoutdate, propertyID, nights, adults, chileren, room);

                    if (DataAcl.Common.checkexpojs(rateCode))
                        googlejs.Visible = true;
                    else
                        googlejs.Visible = false;

                }
                catch (Exception ex)
                {
                    ShowErr("Can't get rate information due to data lost.");
                    HCRS.Errors.WebError.SendErrorEmail(ex, "", HttpContext.Current.Request.Cookies["Hubs1user"]["UserName"].ToString(), "锦江常客网站en");

                    // string message = "错误信息:" + ex.Message + ex.Source + ex.StackTrace + ";引发异常的方法:" + ex.TargetSite.ToString() + ";错误模块:reservation.aspx ; 错误程序:PageLoad";
                    // Hubs1.Net.Error.Log("Bookengine_en/reservation.aspx/Page_Load!", message);
                }


            }

        }

        private void CheckRates(string roomType, string rateClass, string Chickindate, string Chickoutdate, int propertyID, int nights, int adults, int chileren, int room)
        {
            string errmsg;
            bool showGuestInfo = true;
            string plandesc = string.Empty;
            string planstatus = string.Empty;
            string roomdesc = string.Empty;
            string roomname = string.Empty;
            string ratedesc = string.Empty;
            string ratename = string.Empty;
            string responsexml = string.Empty; ;
            string tempCurrencyCode = "";
            string TempCurrenyCode = "";
            string BreakFirst = "";

            //查询数据库缓存表
            //_DataAccessLayer.ClearParameter();
            //_DataAccessLayer.addNewParameter("@Property_id", propertyID);
            //_DataAccessLayer.addNewParameter("@plancode", roomType + "-" + rateClass, 50);
            //_DataAccessLayer.addNewParameter("@Chickindate", Chickindate, 10);
            //_DataAccessLayer.addNewParameter("@Chickoutdate", Chickoutdate, 10);

            //DataTable cachetable = _DataAccessLayer.RunStoreDataTable("Hotel_CheckRate_H_cache");

            //DataRow drdesc = _DataAccessLayer.RunSqlDataRow("select plandesc,roomdesc,roomname from h_plan where property_id=" + propertyID + " and plancode='" + roomType +"-"+ rateClass + "' and languagetype=1");
            //if (drdesc != null)
            //{
            //    //roomname = drdesc["roomname"].ToString();
            //    //roomdesc = drdesc["roomdesc"].ToString();
            //    //plandesc = drdesc["plandesc"].ToString();
            //}
            //else
            //{
            //    roomname = "";
            //    roomdesc = "";
            //    plandesc = "";
            //}



            //
            DataSet myDataSet = null;
            //new HCRS.Implementation.QueryXml().GetNewRateAvailMapSinglePlan(roomType, rateClass, Chickindate, propertyID, nights, adults, chileren, room, 1, out errmsg, out myDataSet);
            GetRateInfo info = new GetRateInfo();
            info.adults = adults;
            info.checkin = Chickindate;
            info.children = chileren;
            //info.currencycode = "";
            //info.filter = "0";
            info.iata = CommonFun.IATA();
            info.language = 1;
            info.nights = nights;
            info.pid = propertyID;
            info.ratecodes = rateClass.Split(',');
            info.roomcodes = roomType.Split(',');
            info.rooms = room;

            myDataSet = HCRS.Implementation.OrderClass.getonlineratemap(info, out errmsg);

            if (errmsg == "Error" || errmsg == "noResponse")
            {
                divpric.InnerHtml = "No rates for this hotel at this moment（Error 011!）";
            }
            else if (errmsg == "noEnoughAvailRoom")
            {
                divpric.InnerHtml = "No rates for this hotel at this moment（Error 012!）";

            }
            else if (myDataSet.Tables[1].Select("gua='CP'").Length > 0)
            {
                divpric.InnerHtml = "No rates for this hotel at this moment（Error 013!）";
            }
            else if (errmsg == "")
            {
                if (myDataSet.Tables[0].Rows.Count != 0)
                {
                    plandesc = myDataSet.Tables[0].Rows[0]["planDesc"].ToString();
                    planstatus = myDataSet.Tables[0].Rows[0]["planStatus"].ToString();
                    roomdesc = myDataSet.Tables[0].Rows[0]["roomDesc"].ToString();
                    roomname = myDataSet.Tables[0].Rows[0]["roomName"].ToString();
                    ratedesc = myDataSet.Tables[0].Rows[0]["rateDesc"].ToString();
                    ratename = myDataSet.Tables[0].Rows[0]["rateName"].ToString();

                }
                ////////////////
                string data = "";
                bool noteaque = false;
                bool noALLOT = false;
                bool noAvStat = false;
                bool noAvStatLos = false;
                string GUARule = "RH";
                string CXLRule = "NP";
                decimal totalMount = 0;
                string dailyPrice = "";

                //if (cachetable.Rows.Count > 0)
                //{
                //    for (int i = 0; i < cachetable.Rows.Count; i++)
                //    {

                //        if (i == 0 && (cachetable.Rows[0]["AvStat"].ToString() == "A" || cachetable.Rows[0]["AvStat"].ToString() == "L"))
                //        {
                //            noAvStatLos = true;
                //        }

                //        GUARule = cachetable.Rows[i]["Gua"].ToString();
                //        CXLRule = cachetable.Rows[i]["Cxl"].ToString();
                //        string AvStat = cachetable.Rows[i]["AvStat"].ToString();
                //        int Allotment = Convert.ToInt32(cachetable.Rows[i]["Allotment"].ToString());
                //        int Maxlos = cachetable.Rows[i]["Maxlos"].ToString() == "" ? 0 : Convert.ToInt32(cachetable.Rows[i]["Maxlos"].ToString());
                //        int Minlos = cachetable.Rows[i]["Minlos"].ToString() == "" ? 0 : Convert.ToInt32(cachetable.Rows[i]["Minlos"].ToString());
                //        decimal priceNoTax = decimal.Round(Convert.ToDecimal(cachetable.Rows[i]["priceNoTax"].ToString()), 2);
                //        //int Allotment = Convert.ToInt32(drcache[0]["Allotment"].ToString());
                //        //string Gua = drcache[0]["Gua"].ToString();
                //        //string Cxl = drcache[0]["Cxl"].ToString();
                //        //string AvStat = drcache[0]["AvStat"].ToString();

                //        totalMount += priceNoTax;
                //        dailyPrice += "|" + cachetable.Rows[i]["Availdate"].ToString() + "," + priceNoTax.ToString();
                //        //核对保证金制度
                //        CheckGua(GUARule);
                //        cachetable.Rows[i]["Gua"] = FGBCommon.GetGuaImage(GUARule);
                //        cachetable.AcceptChanges();

                //    }
                //}
                //else
                //{
                //    pnlGuestInfo.Visible = false;
                //    pnlErr.Visible = true;
                //    ReturnInfo.Visible = false;
                //    //chkChange.Visible = false;
                //    lblErr.Text = "Local data not found,please try again.";
                //}
                if (ppGua)
                {

                    pnlGuestInfo.Visible = false;
                    pnlErr.Visible = true;
                    ReturnInfo.Visible = false;
                    //chkChange.Visible = false;
                    lblErr.Text = "This rome type need deposit prepay guarantee,please contact hotel for reservation. Thank you!";

                }



                ///////////////////
                for (int i = 0; i < myDataSet.Tables[1].Rows.Count; i++)
                {
                    tempCurrencyCode = myDataSet.Tables[1].Rows[i]["currencycode"].ToString();
                    decimal xmlpriceNoTax = decimal.Round(Convert.ToDecimal(myDataSet.Tables[1].Rows[i]["priceNoTax"].ToString()), 2);
                    string xmlGua = myDataSet.Tables[1].Rows[i]["Gua"].ToString();
                    string xmlCxl = myDataSet.Tables[1].Rows[i]["Cxl"].ToString();

                    //    decimal priceNoTax = decimal.Round(Convert.ToDecimal(drcache[0]["priceNoTax"].ToString()), 2);
                    TempCurrenyCode = myDataSet.Tables[1].Rows[i]["currencycode"].ToString();
                    BreakFirst += "," + myDataSet.Tables[1].Rows[i]["breakfastnum"].ToString();

                    totalMount += xmlpriceNoTax;
                    dailyPrice += "|" + myDataSet.Tables[1].Rows[i]["Availdate"].ToString() + "," + xmlpriceNoTax.ToString();


                    //GUARule = xmlGua;
                    //CXLRule = xmlCxl;
                    //CheckGua(GUARule);



                    myDataSet.Tables[1].Rows[i]["Gua"] = FGBCommon.GetGuaImage(xmlGua);
                }

                GUARule = myDataSet.Tables[0].Rows[0]["resvgua"].ToString();
                CXLRule = myDataSet.Tables[0].Rows[0]["resvcxl"].ToString();

                CheckGua(GUARule);

                //////////////////////////
                if (ccGua)
                {
                    //如果需要输入信用卡，就显示信用卡输入筐。

                    PageCC.Visible = true;
                }



                #region 保证金制度描述
                string guarrule = _HotelClass.guarruledetail(propertyID, GUARule, 1);
                GUAdesc.InnerHtml = guarrule;
                #endregion

                #region 取消制度描述
                string cxl = _HotelClass.cxlruledetail(propertyID, CXLRule, 1);

                CXLdesc.InnerHtml = cxl;

                #endregion

                #region 填写表单各数据项
                LabelAdults.Text = adults.ToString();
                //LabelChileren.Text = chileren.ToString();
                // LabelChickIn.Text =_CommonClass.getDate(Chickindate);
                // LabelCheckout.Text = _CommonClass.getDate(Chickoutdate);
                LabelNights.Text = nights.ToString();
                if (plandesc == "")
                    plandesc = "-"; //2007.12.25 andy NA修改为-
                LabelPlanDesc.Text = plandesc;
                LabelRoom.Text = room.ToString();
                if (roomdesc == "")
                    roomdesc = "-";
                lblRoomDesc.Text = roomdesc;
                if (roomname == "")
                    roomname = "-";
                lblRoomName.Text = roomname;
                LabCurrency.Text = tempCurrencyCode;
                #endregion

                #region 税金制度
                _DataAccessLayer.ClearParameter();
                _DataAccessLayer.addNewParameter("@Property_id", propertyID);
                _DataAccessLayer.addNewParameter("@languagetype", 0);
                DataTable MydatatableTAX = _DataAccessLayer.RunStoreDataTable("selectTAXDFB");
                foreach (DataRow dr in MydatatableTAX.Rows)
                {
                    string typeCode = dr["typeCode"].ToString();
                    switch (typeCode)
                    {
                        case "ST":
                            typeCode = "State Tax";
                            break;

                        case "CT":
                            typeCode = "City Tax";
                            break;

                        case "CH":
                            typeCode = "City Hotel Fee";
                            break;
                        case "CO":
                            typeCode = "County Tax";
                            break;
                        case "FT":
                            typeCode = "Federal Tax";
                            break;
                        case "SA":
                            typeCode = "Sales Tax";
                            break;
                        case "RF":
                            typeCode = "Recourse Fee";
                            break;
                        case "SV":
                            typeCode = "Surcharge Penalty";
                            break;
                        case "SC":
                            typeCode = "Service Charge";
                            break;
                        case "OT":
                            typeCode = "Check-in Charge";
                            break;
                        case "MF":
                            typeCode = "Maintenance Fee";
                            break;
                        case "EC":
                            typeCode = "Energy Charge";
                            break;
                        case "PR":
                            typeCode = "Package Rate";
                            break;
                        case "BT":
                            typeCode = "Bed Tax";
                            break;
                        case "VA":
                            typeCode = "Value-added Tax";
                            break;
                        case "SU":
                            typeCode = "Surcharge";
                            break;


                    }
                    dr["typeCode"] = typeCode;

                    string application = dr["application"].ToString();
                    switch (application)
                    {
                        case "RS":
                            application = "per room/stay";
                            break;

                        case "RN":
                            application = "per room/night";
                            break;

                        case "PS":
                            application = "per person/stay";
                            break;
                        case "PN":
                            application = "per person/night";
                            break;


                    }
                    dr["application"] = application;

                    string feetype = dr["method"].ToString();
                    switch (feetype)
                    {
                        case "P":
                            feetype = "base on " + application + " charge " + dr["amount"].ToString() + "％ of total amount as " + typeCode;
                            break;

                        case "M":
                            feetype = "base on " + application + " charge" + dr["amount"].ToString() + "(CNY),as " + typeCode;
                            break;

                    }
                    dr["method"] = feetype;
                    Taxdesc.InnerHtml += typeCode + ": " + feetype + "<br />";
                }



                #endregion

                #region 总价/每日价格/房型描述/价格描述/填写表单各数据项，并写入viewstate供回传
                totalMount = totalMount * room;
                H_ratelist _H_ratelist = new H_ratelist();
                divpric.InnerHtml = _H_ratelist.GetRate(myDataSet.Tables[1], Chickindate, Chickoutdate, nights);
                TotalPrice.InnerHtml = string.Format("{0:C} ", totalMount);
                TotalPrice1.Text = totalMount.ToString();

                decimal Scores = totalMount * exchange;
                ltrScores.Text = "<script language=\"javascript\" type=\"text/javascript\">var Scores=" + Scores + ";</script>";

                LabelAdults.Text = adults.ToString();
                //LabelChileren.Text = chileren.ToString();
                // LabelChickIn.Text =_CommonClass.getDate(Chickindate);
                //LabelCheckout.Text = _CommonClass.getDate(Chickoutdate);
                LabelNights.Text = nights.ToString();
                if (plandesc == "")
                    plandesc = "-"; //2007.12.25 andy NA修改为-
                LabelPlanDesc.Text = plandesc;
                if (room.ToString() == "")
                    LabelRoom.Text = "-";
                else
                    LabelRoom.Text = room.ToString();
                if (roomdesc == "")
                    roomdesc = "-";
                lblRoomDesc.Text = roomdesc;
                if (roomname == "")
                    roomname = "-";
                lblRoomName.Text = roomname;

                ViewState["h_Guarantee"] = GUARule;
                ViewState["h_TotalMount"] = totalMount.ToString();
                ViewState["h_DailyPrice"] = dailyPrice;
                ViewState["Scores"] = Scores;
                ViewState["h_BreakFirst"] = BreakFirst;
                ViewState["h_CurrencyCode"] = TempCurrenyCode;
                #endregion


            }



        }
        private bool LoadHotelInfo(int hotelID)
        {
            #region 读取酒店信息，如果没有对应的酒店，则输出错误提示。



            DataRow dr = _DataAccessLayer.RunSqlDataRow("select * from Hotel where pid=" + hotelID);
            if (dr["Title"] != "")
            {

                lblHotelName.Text = dr["Title_e"].ToString();
                Header.Title = dr["Title_e"].ToString() + " reservation system-step2-input guestInfo";//写页面title
                Hotel_titletel.InnerHtml = "<b>Phone: </b>" + dr["Phone"].ToString();
                address1.InnerHtml = "<b>Address: </b>" + dr["Address1_e"].ToString();
                fax.InnerHtml = "<b>Fax: </b>" + dr["fax"].ToString();
                subtitle.InnerHtml = "<b>Brief Introduction: </b>" + dr["subtitle_e"].ToString();
                imgHotel.ImageUrl = "http://photos.hubs1.net/" + dr["photourl"].ToString();
                //hplShowHotel.NavigateUrl = "show.aspx?hid=" + hotelID.ToString();
                //hplShowHoteltext.NavigateUrl = "show.aspx?hid=" + hotelID.ToString();
                //hplShowHoteltext.Target = "_blank";
                //hplShowHotel.Target = "_blank";
                propertyID = Convert.ToInt32(dr["pid"].ToString());
                lblHoldtime.Text = DataAcl.Common.formatCheckInOut(dr["holdtime"].ToString());
                StringBuilder holdtimeScript = new StringBuilder();
                holdtimeScript.Append("<script language=\"JavaScript\" type=\"text/JavaScript\">");
                holdtimeScript.Append("function validateCheckInTimeDo(obj)");
                holdtimeScript.Append("{");
                holdtimeScript.Append("var s=obj.value;");
                holdtimeScript.Append("if (s>" + dr["holdtime"].ToString() + ") ");
                holdtimeScript.Append("{");
                holdtimeScript.Append("document.getElementById(\"checkintime\").innerHTML=\"<font color=DodgerBlue>Your choice of arrival time has exceeded the hotel’s guarantee time period. Room availability will depend on the circumstances, and the hotel does NOT guarantee the availability.  You might need to provide guarantee when necessary.</font>\";");
                holdtimeScript.Append("}");
                holdtimeScript.Append("else ");
                holdtimeScript.Append("document.getElementById(\"checkintime\").innerHTML=\"\";");
                holdtimeScript.Append("}");
                holdtimeScript.Append("</script>");
                Page.RegisterStartupScript("123", holdtimeScript.ToString());
                return true;
            }
            else
            {
                return false;
                Header.Title = "HUBS1 reservation system-step2-input guestInfo";//写页面title
            }


            #endregion
        }

        public void CheckGua(string guaRule)
        {
            #region 如果保证金制度是CC,显示信用卡输入筐，否则不显示
            if (guaRule.IndexOf("DP") >= 0 || guaRule.IndexOf("PP") >= 0)
            {

                //查询保证金制度描述
                PAYdesc.InnerHtml = "<font color=red>Guarantee payment is required for this room type</font>";
                paymentHtml = "<tr><td ><span class='redtype'><strong>Prepayment is required by the hotel in order to reserve this room type. Reservations cannot be completed unless online prepayment is completed.</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";
                ppGua = true;
                ViewState["payment"] = "PP";
                panelpay.Visible = true;
            }
            else if (guaRule.IndexOf("CC") >= 0)
            {
                PAYdesc.InnerHtml = "<font color=red>Credit Card Guarantee is required for this room type</font>";
                ccGua = true;
            }
            //else
            //{
            //    PAYdesc.InnerHtml = "无需信用卡，无需预付费保证";
            //    paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>我要预付费来确保我的预订</td></tr>";

            //}
            //if (guaRule.IndexOf("CC") < 0)
            //{
            //    // CreditCard.Controls.Clear();

            //    if (guaRule.IndexOf("DP") < 0 || guaRule.IndexOf("PP") < 0)
            //    {

            //        //查询保证金制度描述
            //        PAYdesc.InnerHtml = "No Credit Card or Prepayment Guarantee needed";
            //        paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>I would like to prepay to guarantee my reservation</td></tr>";

            //    }
            //    else
            //    {
            //        PAYdesc.InnerHtml = "<font color=red>本房型需预付费保证</font>";
            //        paymentHtml = "<tr><td ><span class='redtype'><strong>Prepayment is required by the hotel in order to reserve this room type. Reservations cannot be completed unless online prepayment is completed.</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";

            //    }
            //}

            #endregion
        }

        public void Payment(string guaRule)
        {
            #region 如果保证金制度代码包含CC和DP则强制要求付费

            if (guaRule.IndexOf("CC") > 0 || guaRule.IndexOf("DP") > 0)
            {
                paymentHtml = "<tr><td ><span class='redtype'><strong>Prepayment is required by the hotel in order to reserve this room type. Reservations cannot be completed unless online prepayment is completed.</strong></span> <input name='prepay' type='hidden' id='prepay' value='1'></td></tr>";
            }
            else
            {
                paymentHtml = "<tr><td ><input name='prepay' type='checkbox' id='Checkbox1' value='1'>I would like to prepay to guarantee my reservation</td></tr>";
            }

            #endregion
        }
        protected void Button1_Click(object sender, EventArgs e)
        {

            int adult;
            int children;
            int room;
            int nights;
            int property_id;
            string rateclass = ViewState["h_rateclass"].ToString();
            string roomtype = ViewState["h_roomtype"].ToString();
            string checkIn = _CommonClass.getDate(Request.QueryString["ChkIn"]);
            string checkOut = _CommonClass.getDate(Request.QueryString["ChkOUT"]);
            string totalMount = ViewState["h_TotalMount"].ToString();
            string dailyPrice = ViewState["h_DailyPrice"].ToString();
            string plandesc = LabelPlanDesc.Text;
            string roomname = lblRoomName.Text;
            string roomdesc = lblRoomDesc.Text;
            string cancellationPolicy = CXLdesc.InnerHtml;
            string guaranteePolicy = GUAdesc.InnerHtml;
            string taxPolicy = Taxdesc.InnerHtml;
            string fromurl = ViewState["h_fromurl"].ToString();
            string subSource = ViewState["h_subSource"].ToString();
            string verifycode = ViewState["h_verifycode"].ToString();
            string firstName = _CommonClass.VerifySQL(FirstName.Text);
            string lastName = _CommonClass.VerifySQL(LastName.Text);
            string guestEmail = _CommonClass.VerifySQL(GuestEmail.Text);
            string guestPhone = _CommonClass.VerifySQL(GuestPhone.Text);
            string guestMP = _CommonClass.VerifySQL(GuestMP.Text);
            string guestAddressLine1 = _CommonClass.VerifySQL(GuestAddressLine1.Text);
            string remarks = _CommonClass.VerifySQL(Server.HtmlDecode(this.remark.Text.Replace("%", "％")));
            string resvinfo = "";
            string currencyCode = ViewState["h_CurrencyCode"].ToString();
            string breakFirst = ViewState["h_BreakFirst"].ToString();

            int userID;
            string userType;
            string propertyname = "";
            string propertyname_e = "";
            string ccType = "";
            string ccNumber = "";
            string ccName = "";
            string ccMonth = "";
            string ccYear = "";

            decimal scores = Convert.ToDecimal(ViewState["Scores"]);

            //verifycode;
            DateTime updatetime = new DateTime();
            updatetime = DateTime.Now;

            if (_CommonClass.VerifySQL(this.dpdCheckInTime.Text) != "")
            {
                remarks += "<br/>Guest Check In time: " + DataAcl.Common.formatCheckInOut(this.dpdCheckInTime.Text);

                Hubs1.ResvInfoBean resvinfobean = new Hubs1.ResvInfoBean();
                resvinfobean.holdTime = DataAcl.Common.formatCheckInOut(this.dpdCheckInTime.Text);
                resvinfo = Hubs1.ResvInfoUtil.GetResvInfoXML(resvinfobean);

            }
            if (_CommonClass.VerifySQL(this.txtAirInfo.Text) != "")
            {
                remarks += "<br/>Flight information: " + this.txtAirInfo.Text;
            }
            if (this.ckbNoSmooking.Checked)
            {
                remarks += "<br/>Request a no smoking room";
            }
            if (guestMP != "")
            {
                remarks += "<br/>Guest mobile phone:" + guestMP;
            }

            userID = 0;
            userType = "";




            if (LabelAdults.Text == "")
            {
                adult = 0;
            }
            else
            {
                adult = Convert.ToInt32(LabelAdults.Text);
            }
            if (ViewState["h_children"] == "")
            {
                children = 0;
            }
            else
            {
                children = Convert.ToInt32(ViewState["h_children"]);
            }
            if (LabelRoom.Text == "")
            {
                room = 0;
            }
            else
            {
                room = Convert.ToInt32(LabelRoom.Text);
            }
            if (LabelNights.Text == "")
            {
                nights = 0;
            }
            else
            {
                nights = Convert.ToInt32(LabelNights.Text);
            }
            if (ViewState["h_property_id"] == "")
            {
                property_id = 0;
            }
            else
            {
                property_id = Convert.ToInt32(ViewState["h_property_id"]);
            }


            CheckGua(ViewState["h_Guarantee"].ToString());
            if (ppGua)
            {
                ccType = "-";
                ccNumber = "-";
                ccMonth = "00";
                ccYear = "00";
                ccName = "-";
            }
            else if (ccGua)
            {

                ccType = PageCC.ccType;
                ccName = PageCC.ccName;
                ccNumber = PageCC.ccNumber;
                ccMonth = PageCC.ccMonth;
                ccYear = PageCC.ccYear;

            }
            else
            {
                ccType = "VI";
                ccNumber = "-";
                ccMonth = "00";
                ccYear = "00";
                ccName = "-";
            }



            string sql = "select title,title_e from hotel where pid='" + property_id + "' or pid_e='" + property_id + "'";
            DataTable dtHotel = _DataAccessLayer.RunSqlDataTable(sql);
            if (dtHotel.Rows.Count > 0)
            {
                propertyname = dtHotel.Rows[0]["title"].ToString();
                propertyname_e = dtHotel.Rows[0]["title_e"].ToString();
            }
            string spresponse = "";
            if (_DataAccessLayer.RunSqlExists("select * from resvlog where verifycode='" + verifycode + "'"))
            {
                if (_DataAccessLayer.RunSqlExists("select * from resvlog where verifycode='" + verifycode + "' and confnum =''"))
                {
                    spresponse = SP_ResvLog_Upd(breakFirst, currencyCode, userID, userType, property_id, roomtype, rateclass, checkIn, checkOut, updatetime.ToString(), nights, room, firstName, lastName, guestEmail, guestPhone, guestMP, guestAddressLine1, "", "-", "-", "-", "-", ccType, ccNumber, ccName, ccYear, ccMonth, "", IATA, resvinfo, remarks, "", "", "", propertyname, propertyname_e, totalMount, dailyPrice, adult, children, plandesc, roomname, roomdesc, cancellationPolicy, guaranteePolicy, taxPolicy, "", fromurl, 0, subSource, "", "", verifycode);

                }
            }
            else
            {
                spresponse = SP_ResvLog_Add(breakFirst, currencyCode, scores, userID, userType, property_id, roomtype, rateclass, _CommonClass.getDate(checkIn), _CommonClass.getDate(checkOut), updatetime.ToString(), nights, room, firstName, lastName, guestEmail, guestPhone, guestMP, guestAddressLine1, "", "-", "-", "-", "-", ccType, ccNumber, ccName, ccYear, ccMonth, "", IATA, resvinfo, remarks, "", "", "", propertyname, propertyname_e, totalMount, dailyPrice, adult, children, plandesc, roomname, roomdesc, cancellationPolicy, guaranteePolicy, taxPolicy, "", fromurl, 0, subSource, "", "", verifycode);

            }
            if (spresponse == "")
            {
                Response.Redirect("ResvDo.aspx?verifycode=" + verifycode + "&wd=" + System.Web.HttpUtility.UrlEncode(domainurl), false);//跨域高度自适应脚本需要页面重新load一遍，所以不能用servertransfer
                //Server.Transfer("ResvDo.aspx?verifycode=" + verifycode, false);
            }
            else
            {

                ShowErr("System encounter an error when saving reservation information,please try again.");

            }
        }

        private string rndnum(int vcodenum)
        {

            string vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +

            ",q,r,s,t,u,v,w,x,y,z";

            string[] vcarray = vchar.Split(',');

            string vnum = "";

            int temp = -1;

            System.Random rand = new Random();

            for (int i = 1; i < vcodenum + 1; i++)
            {

                if (temp != -1)
                {

                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

                }

                int t = rand.Next(35);

                if (temp != -1 && temp == t)
                {

                    return rndnum(vcodenum);

                }

                temp = t;

                vnum += vcarray[t];

            }
            vnum += DateTime.Now.Ticks.ToString();
            return vnum;

        }


        private string SP_ResvLog_Add(string breakFirst, string currencyCode, decimal scores, int userid, string usertype, int propertyid, string roomtype, string rateclass, string starttime, string deptime, string updatetime, int nights, int room, string guestfirstname, string guestlastname, string guestemail, string guestphone, string guestMP, string guestaddressline1, string guestaddressline2, string guestcity, string guestcountry, string gueststate, string guestzip, string cctype, string ccnumber, string ccname, string ccexpyear, string ccexpmonth, string frequentguestid, string iata, string resvinfo, string remarks, string confnum, string cxlnum, string status, string propertyname, string propertyname_e, string totalmount, string dailyprice, int adults, int children, string plandesc, string roomname, string roomdesc, string canclerule, string guaranteerule, string taxrule, string incomingcall, string fromurl, int deleted, string SubSource, string lastuser, string lastusertype, string verifycode)
        {
            string errmsg = "";
            string cardnumber = LoginInfo.Member != null ? LoginInfo.Member.UserId : string.Empty;
            string cardclass = "", cardclassname = "";
            if (cardnumber != "")
            {
                //lakeport.WebReference.MemberSummery mms = new WestLake.LakeMember().memberconsume(cardnumber);
                cardclass = LoginInfo.Member != null ? LoginInfo.Member.CardLevel : string.Empty;
                cardclassname = LoginInfo.Member != null ? LoginInfo.Member.CardLevel : string.Empty;
            }
            string spcode = ViewState["spcode"].ToString();
            bool isspecial = (spcode.Length > 0);

            bool islock = true;
            string freezeno = "";
            bool isexec = false;
            bool isscore = (Request.Form.Get("chkIsScore") != null);
            if (isscore)
            {
                //islock=;//积分冻结

                //if (WestLake.LakeScore.LockScore(verifycode, scores, cardnumber, out freezeno))
                //{
                //    isexec = true;
                //}
                //else
                //{
                //    //return "积分冻结失败，暂时无法使用积分兑换，请稍后预订或检查积分总额是否不足";
                //    return freezeno;
                //}
                isexec = true;
            }
            else
            {
                scores = 0;
                isexec = true;
                islock = true;
            }



            string jremark = "";
            string comment = "";

            if (cardnumber.Length > 0 && DataAcl.Common.isserverhotel(propertyid.ToString()))
            {
                iata = PIATA;
                //jremark += "<br/>【+】";
                //jremark += "<br/>此订单为常客预定";
                jremark += "<br/> Card Number:" + cardnumber;
                jremark += "<br/>Level:" + cardclassname;
                if (isspecial)
                {
                    jremark += "<br/>Special Code:" + spcode;
                }
                if (isscore)
                {
                    jremark += "<br/>Free stays,Spend <font color=red>" + scores.ToString() + "</font> Jin Jiang Prestige points<br> Freeze No:" + freezeno;
                }
                remarks += jremark;
                comment = GetspecialXml(cardnumber, cardclass, (isscore ? "1" : "0"), (room * nights).ToString(), scores.ToString(), freezeno, spcode, "", "", "", "", "", "", "", "");
            }

            _DataAccessLayer.ClearParameter();
            _DataAccessLayer.addNewParameter("@userid", userid);
            _DataAccessLayer.addNewParameter("@usertype", usertype, 50);
            _DataAccessLayer.addNewParameter("@propertyid", propertyid);
            _DataAccessLayer.addNewParameter("@roomtype", roomtype, 50);
            _DataAccessLayer.addNewParameter("@rateclass", rateclass, 50);
            _DataAccessLayer.addNewParameter("@starttime", starttime, 10);
            _DataAccessLayer.addNewParameter("@deptime", deptime, 10);
            _DataAccessLayer.addNewParameter("@updatetime", Convert.ToDateTime(updatetime).ToString("u").Replace("Z", ""), 20);
            _DataAccessLayer.addNewParameter("@nights", nights);
            _DataAccessLayer.addNewParameter("@room", room);
            _DataAccessLayer.addNewParameter("@guestfirstname", guestfirstname, 50);
            _DataAccessLayer.addNewParameter("@guestlastname", guestlastname, 50);
            _DataAccessLayer.addNewParameter("@guestemail", guestemail, 50);
            _DataAccessLayer.addNewParameter("@guestphone", guestphone, 50);
            _DataAccessLayer.addNewParameter("@guestMP", guestMP, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline1", guestaddressline1, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline2", guestaddressline2, 50);
            _DataAccessLayer.addNewParameter("@guestcity", guestcity, 50);
            _DataAccessLayer.addNewParameter("@guestcountry", guestcountry, 50);
            _DataAccessLayer.addNewParameter("@gueststate", gueststate, 50);
            _DataAccessLayer.addNewParameter("@guestzip", guestzip, 50);
            _DataAccessLayer.addNewParameter("@cctype", cctype, 50);
            _DataAccessLayer.addNewParameter("@ccnumber", ccnumber, 50);
            _DataAccessLayer.addNewParameter("@ccname", ccname, 50);
            _DataAccessLayer.addNewParameter("@ccexpyear", ccexpyear, 50);
            _DataAccessLayer.addNewParameter("@ccexpmonth", ccexpmonth, 50);
            _DataAccessLayer.addNewParameter("@frequentguestid", frequentguestid, 50);
            _DataAccessLayer.addNewParameter("@iata", iata, 50);
            _DataAccessLayer.addNewParameter("@resvinfo", resvinfo, 500);
            _DataAccessLayer.addNewParameter("@remarks", remarks);
            _DataAccessLayer.addNewParameter("@confnum", confnum, 50);
            _DataAccessLayer.addNewParameter("@cxlnum", cxlnum, 50);
            _DataAccessLayer.addNewParameter("@status", status, 50);
            _DataAccessLayer.addNewParameter("@propertyname", propertyname, 500);
            _DataAccessLayer.addNewParameter("@propertyname_e", propertyname_e, 500);
            _DataAccessLayer.addNewParameter("@totalmount", totalmount, 50);
            _DataAccessLayer.addNewParameter("@dailyprice", dailyprice, 500);
            _DataAccessLayer.addNewParameter("@adults", adults);
            _DataAccessLayer.addNewParameter("@children", children);
            _DataAccessLayer.addNewParameter("@plandesc", plandesc, 500);
            _DataAccessLayer.addNewParameter("@roomname", roomname, 500);
            _DataAccessLayer.addNewParameter("@roomdesc", roomdesc, 500);
            _DataAccessLayer.addNewParameter("@canclerule", canclerule, 500);
            _DataAccessLayer.addNewParameter("@guaranteerule", guaranteerule, 500);
            _DataAccessLayer.addNewParameter("@taxrule", taxrule, 500);
            _DataAccessLayer.addNewParameter("@incomingcall", incomingcall, 50);
            _DataAccessLayer.addNewParameter("@fromurl", fromurl, 255);
            _DataAccessLayer.addNewParameter("@deleted", deleted);
            _DataAccessLayer.addNewParameter("@SubSource", SubSource, 50);
            _DataAccessLayer.addNewParameter("@lastuser", lastuser, 50);
            _DataAccessLayer.addNewParameter("@lastusertype", lastusertype, 50);
            _DataAccessLayer.addNewParameter("@verifycode", verifycode, 50);
            _DataAccessLayer.addNewParameter("@getstatus", 0);
            _DataAccessLayer.addNewParameter("@flgorder", 0);
            _DataAccessLayer.addNewParameter("@departure", "", 10);
            _DataAccessLayer.addNewParameter("@payment", ViewState["payment"].ToString(), 50);
            _DataAccessLayer.addNewParameter("@cardnumber", cardnumber);
            _DataAccessLayer.addNewParameter("@isscore", isscore);
            _DataAccessLayer.addNewParameter("@isspecial", isspecial);
            _DataAccessLayer.addNewParameter("@jremark", jremark, 500);
            _DataAccessLayer.addNewParameter("@score", scores);
            _DataAccessLayer.addNewParameter("@islock", islock);
            _DataAccessLayer.addNewParameter("@isexec", isexec);
            _DataAccessLayer.addNewParameter("@freezeno", freezeno, 50);
            _DataAccessLayer.addNewParameter("@comment", comment, 500);

            _DataAccessLayer.addNewParameter("@CurrencyCode", currencyCode, 5);
            _DataAccessLayer.addNewParameter("@Breakfast", breakFirst, 50);
            _DataAccessLayer.RunStore("FGB_JJ_ResvLog_Add");
            //CommonDataAccess.ExecInsertProcedure("FGB_JJ_ResvLog_Add", "@,,,,,", "string,int,", new object[] { });


            if (_DataAccessLayer.ErrorMsg.Length > 2)
            {
                return _DataAccessLayer.ErrorMsg;
            }
            else
            {

                return errmsg;
            }

        }

        private string SP_ResvLog_Upd(string breakFirst, string currencyCode, int userid, string usertype, int propertyid, string roomtype, string rateclass, string starttime, string deptime, string updatetime, int nights, int room, string guestfirstname, string guestlastname, string guestemail, string guestphone, string guestMP, string guestaddressline1, string guestaddressline2, string guestcity, string guestcountry, string gueststate, string guestzip, string cctype, string ccnumber, string ccname, string ccexpyear, string ccexpmonth, string frequentguestid, string iata, string resvinfo, string remarks, string confnum, string cxlnum, string status, string propertyname, string propertyname_e, string totalmount, string dailyprice, int adults, int children, string plandesc, string roomname, string roomdesc, string canclerule, string guaranteerule, string taxrule, string incomingcall, string fromurl, int deleted, string SubSource, string lastuser, string lastusertype, string verifycode)
        {
            string errmsg = "";
            _DataAccessLayer.ClearParameter();
            _DataAccessLayer.addNewParameter("@userid", userid);
            _DataAccessLayer.addNewParameter("@usertype", usertype, 50);
            _DataAccessLayer.addNewParameter("@propertyid", propertyid);
            _DataAccessLayer.addNewParameter("@roomtype", roomtype, 50);
            _DataAccessLayer.addNewParameter("@rateclass", rateclass, 50);
            _DataAccessLayer.addNewParameter("@starttime", starttime, 10);
            _DataAccessLayer.addNewParameter("@deptime", deptime, 10);
            _DataAccessLayer.addNewParameter("@updatetime", Convert.ToDateTime(updatetime).ToString("u").Replace("Z", ""), 20);
            _DataAccessLayer.addNewParameter("@nights", nights);
            _DataAccessLayer.addNewParameter("@room", room);
            _DataAccessLayer.addNewParameter("@guestfirstname", guestfirstname, 50);
            _DataAccessLayer.addNewParameter("@guestlastname", guestlastname, 50);
            _DataAccessLayer.addNewParameter("@guestemail", guestemail, 50);
            _DataAccessLayer.addNewParameter("@guestphone", guestphone, 50);
            _DataAccessLayer.addNewParameter("@guestMP", guestMP, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline1", guestaddressline1, 50);
            _DataAccessLayer.addNewParameter("@guestaddressline2", guestaddressline2, 50);
            _DataAccessLayer.addNewParameter("@guestcity", guestcity, 50);
            _DataAccessLayer.addNewParameter("@guestcountry", guestcountry, 50);
            _DataAccessLayer.addNewParameter("@gueststate", gueststate, 50);
            _DataAccessLayer.addNewParameter("@guestzip", guestzip, 50);
            _DataAccessLayer.addNewParameter("@cctype", cctype, 50);
            _DataAccessLayer.addNewParameter("@ccnumber", ccnumber, 50);
            _DataAccessLayer.addNewParameter("@ccname", ccname, 50);
            _DataAccessLayer.addNewParameter("@ccexpyear", ccexpyear, 50);
            _DataAccessLayer.addNewParameter("@ccexpmonth", ccexpmonth, 50);
            _DataAccessLayer.addNewParameter("@frequentguestid", frequentguestid, 50);
            _DataAccessLayer.addNewParameter("@iata", iata, 50);
            _DataAccessLayer.addNewParameter("@resvinfo", resvinfo, 500);
            _DataAccessLayer.addNewParameter("@remarks", remarks);
            _DataAccessLayer.addNewParameter("@confnum", confnum, 50);
            _DataAccessLayer.addNewParameter("@cxlnum", cxlnum, 50);
            _DataAccessLayer.addNewParameter("@status", status, 50);
            _DataAccessLayer.addNewParameter("@propertyname", propertyname, 500);
            _DataAccessLayer.addNewParameter("@propertyname_e", propertyname_e, 500);
            _DataAccessLayer.addNewParameter("@totalmount", totalmount, 50);
            _DataAccessLayer.addNewParameter("@dailyprice", dailyprice, 500);
            _DataAccessLayer.addNewParameter("@adults", adults);
            _DataAccessLayer.addNewParameter("@children", children);
            _DataAccessLayer.addNewParameter("@plandesc", plandesc, 500);
            _DataAccessLayer.addNewParameter("@roomname", roomname, 500);
            _DataAccessLayer.addNewParameter("@roomdesc", roomdesc, 500);
            _DataAccessLayer.addNewParameter("@canclerule", canclerule, 500);
            _DataAccessLayer.addNewParameter("@guaranteerule", guaranteerule, 500);
            _DataAccessLayer.addNewParameter("@taxrule", taxrule, 500);
            _DataAccessLayer.addNewParameter("@incomingcall", incomingcall, 50);
            _DataAccessLayer.addNewParameter("@fromurl", fromurl, 255);
            _DataAccessLayer.addNewParameter("@deleted", deleted);
            _DataAccessLayer.addNewParameter("@SubSource", SubSource, 50);
            _DataAccessLayer.addNewParameter("@lastuser", lastuser, 50);
            _DataAccessLayer.addNewParameter("@lastusertype", lastusertype, 50);
            _DataAccessLayer.addNewParameter("@verifycode", verifycode, 50);

            _DataAccessLayer.addNewParameter("@CurrencyCode", currencyCode, 5);
            _DataAccessLayer.addNewParameter("@Breakfast", breakFirst, 50);

            _DataAccessLayer.RunStore("FGB_JJ_ResvLog_Mod");


            if (_DataAccessLayer.ErrorMsg.Length > 2)
            {
                //Response.Write(_DataAccessLayer.ErrorMsg); //输出错误信息
                return _DataAccessLayer.ErrorMsg;
            }
            else
            {
                return errmsg;
            }

        }


        private void ShowErr(string errmsg)
        {
            pnlGuestInfo.Visible = false;
            //chkChange.Visible = false;
            ReturnInfo.Visible = false;
            pnlErr.Visible = true;
            lblErr.Text = errmsg;
        }


        private string GetspecialXml(string memberno, string memberclass, string isfree, string room, string score, string freezeno, string salecode, string airtype, string airno, string airamount, string f1, string f2, string f3, string f4, string f5)
        {
            StringBuilder str = new StringBuilder();
            str.Append("<memberinfo> ");
            str.Append(" <memberno>" + memberno + "</memberno> ");
            str.Append(" <memberclass>" + memberclass + "</memberclass> ");
            str.Append(" <isfree>");
            if (isfree == "1")
                str.Append("Y");
            else
                str.Append("N");
            str.Append("</isfree> ");
            str.Append(" <room>" + room + "</room> ");
            str.Append(" <score>" + score + "</score> ");
            str.Append(" <freezeno>" + freezeno + "</freezeno> ");
            str.Append(" <salecode>" + salecode + "</salecode> ");
            str.Append(" <airtype>" + airtype + "</airtype> ");
            str.Append(" <airno>" + airno + "</airno> ");
            str.Append(" <airamount>" + airamount + "</airamount> ");
            str.Append("<f1></f1>");
            str.Append("<f2></f2>");
            str.Append("<f3></f3>");
            str.Append("<f4></f4>");
            str.Append("<f5></f5>");
            str.Append("</memberinfo>");
            return str.ToString();
        }
    }
}